<?php
/**
 * XiaoYuanMenSuo-PHP
 * ==================================================================
 * CopyRight © 2017-2099 广州米袋软件有限公司
 * 官网地址：http://www.mdsoftware.cn
 * 售后技术支持：15017566075
 * ------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下
 * 对本程序代码进行修改和使用；不允许对本程序代码以任何目的的再发布。
 * ==================================================================
 *
 * @Author ZHC(codecookies@163.com)
 * @Date 2021-12-13 19:27 星期一
 * @Version 1.0
 */

namespace app\controller\api;


use app\model\AdminSchool;
use app\model\AdminStaff;
use app\model\AdminUser;
use app\model\AdminVisitRegistrationLog;
use app\model\AdminVisitRegistrationPicture;
use app\common\service\wxapi\CheckIdCard;
use app\model\AdminVisitUser;
use app\util\ReturnCode;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\Response;

class WxApiIndex extends Base
{
    // 来访登记列表
    public function visitLogList(): Response
    {
        $api_auth = $this->request->header('Api-Auth');
        $page = $this->request->get('page');
        if (!$api_auth || !$page){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        $user = (new AdminVisitUser())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        if (!$user){
            return $this->buildFailed(ReturnCode::CACHE_READ_ERROR, '用户未登录');
        }

        $log_list = (new AdminVisitRegistrationLog())->with('schoolData')->where(['user_id' => $user->id, 'is_delete' => 0])->paginate(['list_rows'=> 10, 'page' => $page])->toArray();
        if ($log_list['data']){
            foreach ($log_list['data'] as &$log){
                $log['visiting_time'] = date('Y-m-d H:i:s', $log['visiting_time']);
                unset($log['openid']);
            }
            unset($log);
        }
        return $this->buildSuccess([
            'list' => $log_list['data'],
            'per_page' => $log_list['per_page'],
            'current_page' => $log_list['current_page'],
            'last_page' => $log_list['last_page'],
        ], '成功');
    }

    // 来访登记
    public function toVisit(): Response
    {
        $school_id = $this->request->post('school_id');
        $name = $this->request->post('name');
        $sex = $this->request->post('sex');
        $id_card = $this->request->post('id_card');
        $phone = $this->request->post('phone');
        $visiting_object = $this->request->post('visiting_object');
        $visiting_time = $this->request->post('visiting_time');
        $api_auth = $this->request->header('Api-Auth'); //用户登录凭证
        $visiting_content = $this->request->post('visiting_content');
        $picture_list = $this->request->post('picture_list');

        if (!$school_id || !$name || !$sex || !$id_card || !$phone || !$visiting_object || !$visiting_time || !$api_auth) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        //判断手机
        if (!validatePhone($phone)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请输入正确的手机号');
        }
        //判断身份证
        if (!CheckIdCard::check($id_card)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请填写正确的身份证');
        }

        $user = (new AdminVisitUser())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        if (!$user){
            return $this->buildFailed(ReturnCode::CACHE_READ_ERROR, '用户未登录');
        }

        //新增数据
        $Db = new Db();
        $Db::startTrans();
        try{
            $school_name = (new AdminSchool())->where(['id' => $school_id])->value('name');
            $form = new AdminVisitRegistrationLog();
            $data = [
                'school_id' => $school_id,
                'school_name' => $school_name ? $school_name : '',
                'name' => $name,
                'sex' => $sex,
                'id_card' => $id_card,
                'phone' => $phone,
                'visiting_object' => $visiting_object,
                'visiting_time' => strtotime($visiting_time),
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
                'visiting_content' => $visiting_content,
                'user_id' => $user->id,
            ];
            $res = $form->save($data);
            if (!$res) {
                $Db::rollback();
                throw new Exception('来访登记失败');
            }

            if ($picture_list){
                $picture_list = json_decode($picture_list);
                foreach ($picture_list as $pic){
                    $picture = new AdminVisitRegistrationPicture();
                    $pic_data = [
                        'visit_id' => $form->id,
                        'picture_url' => $pic,
                        'is_delete' => 0,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    $pic_res = $picture->save($pic_data);
                    if (!$pic_res) {
                        $Db->rollback();
                        throw new Exception('来访登记失败');
                    }
                }
                unset($pic);
            }
            $Db::commit();
            return $this->buildSuccess(['visit_log_id' => $form->id], '登记成功');
        }catch (\Exception $exception){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '来访登记失败'.$exception->getMessage());
        }
    }

    //来访详情
    public function visitDetail(): Response
    {
        $visit_id = $this->request->get('visit_id');
        $type = $this->request->get('type');
        $api_auth = $this->request->header('Api-Auth');
        if (!$visit_id || !$api_auth || !$type){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        if ($type == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $api_auth])->find();
        }elseif($type == 'worker'){
            $user = (new AdminStaff())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        }elseif($type == 'visit'){
            $user = (new AdminVisitUser())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        }else{}
        if (!$user){
            return $this->buildFailed(ReturnCode::CACHE_READ_ERROR, '用户未登录');
        }

        $query = (new AdminVisitRegistrationLog())->with(['schoolData','pictureData'])->where(['id' => $visit_id, 'is_delete' => 0]);
        if ($type == 'admin' || $type == 'worker'){
            $query->where(['school_id' => $user->school_id]);
        }else{
            $query->where(['user_id' => $user->id]);
        }
        $log = $query->find();
        if ($log){
            $log->visiting_time = date('Y-m-d', $log->visiting_time);
        }

        return $this->buildSuccess(['log' => $log ? $log->toArray() : []], '成功');
    }
}